package com.bodacn.keypoint;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import org.json.JSONArray;
import org.json.JSONException;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;


/**
 * A simple {@link Fragment} subclass.
 */
public class FragmentTransScan extends Fragment implements View.OnClickListener {
    public static String TAG= FragmentScan.class.getName();
    public static final int msgFocusBarcode = 1001;
    public static final int MSG_SCANBARCODE = 9001;
    public static final int MSG_PROCLIST =9002;
    public static final int MSG_SelectData =9003;
    public static final int MSG_TotalData=9004;

    //用于将Activity中的参数传给Fragment
    private Map<String,Object> fragmentParams=new HashMap<String,Object>();
    ReentrantLock reentrantLock = new ReentrantLock();
    //用于与主Activity通讯;
    private Handler mainHandler;
    //全局变量
    Toast curToast;
    String curLoginUserNo,curLoginUser,curServiceUrl="",curServiceDir="",curDepartNo,curDepart,curFactory,CPUID;
    Button btn_find,btn_addProc,btn_clearProc,btn_refresh;
    ImageButton btn_editBarcode;
    ListView procList,totalList;
    TextView txt_HintInfo,txt_OrderNo,txt_StyleNo,txt_StyleSort,txt_PO,txt_Color,txt_Size,txt_DBH,txt_ReadyScan,txt_OwenNum;
    EditText edt_barcode;
    JSONArray resultJSON, procJSON,headJSON,selectJSON,totalJSON;
    String KeyGuid= UUID.randomUUID().toString().toUpperCase();
    LinearLayout templetlisthead;
    ListView selectTempletList;
    String selWorkNo="",selWorkName="",selPrWorkNo="";
    //判断是否为数字，不然不转
    public static boolean isNumeric(String str){
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public FragmentTransScan() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //得到Activity的Handler,用于发消息给主Activity;
        MainActivity activity=(MainActivity) getActivity();
        mainHandler=activity.mainHandler;
        //加接口监听
        activity.setTransParamsListenerTransScan(new MainActivity.OnTransParamsListenerTransScan() {
            @Override
            public void TransParams(Map<String, Object> mParams) {
                if (mParams!=null) {
                    try {
                        String paramComm= mParams.get("ParamComm").toString();
                        if (paramComm=="LoginParam")
                        {
                            Log.d(this.getClass().getName(),"LoginParam------------------>1");
                            //传递登陆参数信息;
                            curLoginUserNo=mParams.get("LoginUserNo").toString();
                            curLoginUser=mParams.get("LoginUser").toString();
                            curServiceUrl=mParams.get("ServiceUrl").toString();
                            curServiceDir= mParams.get("ServiceDir").toString();
                            curDepartNo=mParams.get("DepartNo").toString();
                            curDepart=mParams.get("Depart").toString();
                            curFactory=mParams.get("Factory").toString();
                            CPUID=mParams.get("CPUID").toString();
                            Log.d(this.getClass().getName(),"LoginParam------------------>2");
                            KeyGuid= UUID.randomUUID().toString().toUpperCase();
                            //发消息置焦点
                            Message msg =new Message();
                            msg.what = msgFocusBarcode;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if ((paramComm=="Barcode")){
                            String barcode=mParams.get("Barcode").toString();
                            edt_barcode.setText(barcode);
                            searchBarcodeData(barcode,txt_OrderNo.getText().toString(),txt_StyleNo.getText().toString(),txt_StyleSort.getText().toString());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }






    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getActivity().getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }
    //设置焦点到扫描输入框
    private void setEditBarcodeFocus()
    {
        //设置焦点
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.Start");
        if (edt_barcode!=null) {
            edt_barcode.selectAll();
            edt_barcode.setFocusable(true);
            edt_barcode.setFocusableInTouchMode(true);
            edt_barcode.requestFocus();
            edt_barcode.requestFocusFromTouch();
            hideIM(getView());
            hideBottomUIMenu();
        }
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.End");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_trans_scan, container, false);
        InitView(root);
        System.out.println(this.getClass().getName()+"_onCreateView");
        return root;
    }
    //初始化;
    public void InitView(View view){
        procList=view.findViewById(R.id.procList);
        procList.setFocusable(false);
        procList.setFocusableInTouchMode(false);
        totalList=(ListView) view.findViewById(R.id.totalList);
        totalList.setFocusable(false);
        totalList.setFocusableInTouchMode(false);
        btn_addProc=(Button)view.findViewById(R.id.btn_addProc);
        btn_addProc.setOnClickListener(this);
        btn_clearProc=(Button)view.findViewById(R.id.btn_clearProc);
        btn_clearProc.setOnClickListener(this);
        btn_refresh=(Button)view.findViewById(R.id.btn_refresh);
        btn_refresh.setOnClickListener(this);
        btn_find=(Button)view.findViewById(R.id.btn_find);
        btn_find.setOnClickListener(this);
        btn_editBarcode=(ImageButton)view.findViewById(R.id.btn_editBarcode);
        btn_editBarcode.setOnClickListener(this);
        btn_editBarcode.setFocusable(false);
        btn_editBarcode.setFocusableInTouchMode(false);
        view.findViewById(R.id.btn_Query).setOnClickListener(this);
        //界面Edit;
        edt_barcode=(EditText)view.findViewById(R.id.edt_barcode);
        edt_barcode.setInputType(InputType.TYPE_NULL);
        edt_barcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    if ((event.getAction()==KeyEvent.ACTION_DOWN)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                        //隐藏键盘
                        hideIM(v);
                        if (edt_barcode.getText().length()==0) {
                            curToast.setText(getString(R.string.PleaseInputBarcode));
                            curToast.show();
                        } else {
                            searchBarcodeData(edt_barcode.getText().toString(),txt_OrderNo.getText().toString(), txt_StyleNo.getText().toString(),txt_StyleSort.getText().toString());
                        }
                        //未有焦点
                        if (edt_barcode.isFocused()==false){
                            //发消息置焦点
                            Message msg =new Message();
                            msg.what = msgFocusBarcode;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        } else edt_barcode.selectAll();
                    }

                }
                return false;
            }
        });
        edt_barcode.requestFocus();
        edt_barcode.requestFocusFromTouch();
        txt_HintInfo=(TextView)view.findViewById(R.id.txt_HintInfo);
        txt_OrderNo=(TextView)view.findViewById(R.id.txt_OrderNo);
        txt_StyleNo=(TextView)view.findViewById(R.id.txt_StyleNo);
        txt_StyleSort=(TextView)view.findViewById(R.id.txt_StyleSort);
        txt_PO=(TextView)view.findViewById(R.id.txt_PO);
        txt_Color=(TextView)view.findViewById(R.id.txt_Color);
        txt_Size=(TextView)view.findViewById(R.id.txt_Size);
        txt_DBH=(TextView)view.findViewById(R.id.txt_DBH);
        txt_ReadyScan=(TextView)view.findViewById(R.id.txt_ReadyScan);
        txt_OwenNum=(TextView)view.findViewById(R.id.txt_OwenNum);
        //初始提醒;
        curToast = Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT);

    }


    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+getActivity().getPackageName()+"/"+ R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(getActivity(), notification);
        r.play();

    }
    //刷新缸布列表;
    private void searchBarcodeData(String BarcodeParam,String OrderNoParam,String StyleNoParam,String StyleSortParam)
    {
        String HaveProcParam="N";
        if (procJSON!=null&&procJSON.length()>0) HaveProcParam="Y";
        String SqlComm="Exec KeyPoint_TransWorkScan @Barcode='" + BarcodeParam + "',@OrderNo='" + OrderNoParam + "',@StyleNo='" + StyleNoParam+ "',@StyleSort='" + StyleSortParam
                + "',@OPERTYPE='SCANBARCODE',@UserNo='"+curLoginUserNo+ "',@HaveProc='"+HaveProcParam+ "',@KeyGuid='"+KeyGuid+"',@TermNo='"+MainApplication.TermNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onClick(View v) {
        hideIM(v);
        switch (v.getId()){
            case R.id.btn_find:
                if (edt_barcode.getText().length()==0) {
                    curToast.setText(getString(R.string.PleaseInputBarcode));
                    curToast.show();
                } else //执行查询;
                {
                    searchBarcodeData(edt_barcode.getText().toString(), txt_OrderNo.getText().toString(), txt_StyleNo.getText().toString(),txt_StyleSort.getText().toString());
                }
                break;
            case R.id.btn_clearProc:
                TransProcList("ClearProc","","","");
                hideIM(v);
                break;
            case R.id.btn_addProc:
                if (txt_OrderNo.getText().toString().length()>0)
                    showSelectProc(txt_OrderNo.getText().toString(),txt_StyleNo.getText().toString(),txt_StyleSort.getText().toString());
                else{
                    curToast.setText("请先扫描条码找出合约！");
                    curToast.show();
                }
                hideIM(v);
                break;
            case R.id.btn_editBarcode:
                edt_barcode.setInputType(InputType.TYPE_CLASS_TEXT);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edt_barcode,InputMethodManager.SHOW_FORCED);
                break;
            case R.id.btn_refresh:
                refreshTotal();
                break;
            case R.id.btn_Query:
                Intent tmpQueryIntent=new Intent(getContext(),QueryActivity.class);
                Bundle paramBundle=new Bundle();
                paramBundle.putString("LoginUserNo", curLoginUserNo);
                paramBundle.putString("LoginUser",curLoginUser);
                paramBundle.putString("CurDepartNo",curDepartNo);
                paramBundle.putString("CurDepart",curDepart);
                paramBundle.putString("CurFactory",curFactory);
                paramBundle.putString("ServiceUrl",curServiceUrl);
                paramBundle.putString("ServiceDir",curServiceDir);
                paramBundle.putString("CPUID",CPUID);
                paramBundle.putString("QueryTitle", "转移印扫描查询");
                paramBundle.putString("OrderNo",txt_OrderNo.getText().toString());
                paramBundle.putString("StyleNo",txt_StyleNo.getText().toString());
                paramBundle.putString("StyleSort",txt_StyleSort.getText().toString());
                paramBundle.putString("NeedOrder","NO");
                tmpQueryIntent.putExtras(paramBundle);
                startActivity(tmpQueryIntent);
                break;
            default:
                break;
        }
    }
    //刷新数据
    private void refreshTotal(){
        try {
            totalJSON=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        TotalListAdapter totalListAdapter = new TotalListAdapter(getContext());
        totalList.setAdapter(totalListAdapter);
        String SqlComm = "Exec KeyPoint_TransGetTotal @OPERTYPE='TotalList',@UserNo='" + curLoginUserNo
                + "',@DepartNo='" + curDepartNo+ "',@CPUID='" + CPUID + "',@TermNo='"+ MainApplication.TermNo +"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }


    //数据适配器，继承自BaseAdapter;
    private final class SelectTempletListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public SelectTempletListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        public  String TrnasValue(String params)
        {
            if ((params.toUpperCase()=="NULL".toUpperCase())||(params=="0")||(params=="0.0"))
                return "";
            else return params;
        }
        @Override
        public int getCount() {
            //每页行数
            return selectJSON.length();
        }
        @Override
        public Object getItem(int position) {
            try {
                if (position<selectJSON.length())
                    return selectJSON.getJSONArray(position);
                else
                    return null;
            } catch (JSONException e)
            {
                e.printStackTrace();
                System.out.println("getItem取JSON数据出错!");
                return  null;
            }
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.select_templet_item, null, false);
            //变换背景色
            /*
            if (position%2==1) {
                view.setBackgroundColor(getResources().getColor(R.color.content));
            }
            */
            int pullVatListWidth=parent.getWidth();
            view.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,60));
            //转换分页码;
            int curPosition= position;
            String tmpValue;
            int color = getResources().getColor(R.color.text_black);
            if (curPosition<selectJSON.length()) {
                try {
                    Log.d(TAG, "getView()----------------------------------------------------->" + position);
                    if (selectJSON.optJSONObject(curPosition).has("ConColor") == true) {
                        tmpValue = selectJSON.optJSONObject(curPosition).getString("ConColor");
                        color=GetColorValue(tmpValue);
                    }
                    for (int i = 0; i < headJSON.length(); i++)
                        if (headJSON.optJSONObject(i).has("TitleText") == true) {
                            try {
                                String TitleName = headJSON.optJSONObject(i).getString("TitleName");
                                if (selectJSON.optJSONObject(curPosition).has(TitleName)==true) tmpValue= selectJSON.optJSONObject(curPosition).getString(TitleName);
                                else tmpValue="unReturn";
                                int TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                                float txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                                int AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                                TextView tv = new TextView(view.getContext());
                                tv.setText(TrnasValue(tmpValue));
                                tv.setWidth((int) txtWidth);
                                tv.setTextColor(color);
                                tv.setGravity(Gravity.CENTER_VERTICAL);
                                if (headJSON.optJSONObject(i).has("Align")==true) {
                                    int Align;
                                    Align = headJSON.optJSONObject(i).getInt("Align");
                                    switch (Align) {
                                        case 0:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                            break;
                                        case 1:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                            break;
                                        case 2:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                            break;
                                        default:
                                            tv.setGravity(Gravity.CENTER_VERTICAL);
                                            break;
                                    }
                                }
                                tv.setTextSize(TxtSize);
                                //添加到View中;
                                if (AutoZoom == 1)
                                    ((LinearLayout)view).addView(tv, new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                                else ((LinearLayout)view).addView(tv);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
            return view;
        }
    }


    //显示工序选择
    private void showSelectProc(String paramOrderNo,String paramStyleNo,String paramStyleSort){
        try {
            headJSON=new JSONArray("[{\"TitleName\":\"SerNo\",\"TitleText\":\"序号\",\"TxtSize\":18,\"TxtWidth\":80,\"AutoZoom\":0,\"Align\":0,\"Color\":\"Blue\"}," +
                    "{\"TitleName\":\"WorkNo\",\"TitleText\":\"工序号\",\"TxtSize\":18,\"TxtWidth\":100,\"AutoZoom\":0,\"Align\":0,\"Color\":\"Blue\"},"+
                    "{\"TitleName\":\"WorkName\",\"TitleText\":\"工序名称\",\"TxtSize\":18,\"TxtWidth\":200,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"}]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //创建布局
        String dgCaption="工序选择";
        LayoutInflater inflater=this.getLayoutInflater();
        final View selectTemplet=inflater.inflate(R.layout.select_templet, null);
        templetlisthead=selectTemplet.findViewById(R.id.templetlisthead);
        //创建表头;
        CreateListHead();
        //Activity.findViewById最终还是会调用View.findViewById
        selectTempletList=selectTemplet.findViewById(R.id.selectTempletList);
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setView(selectTemplet).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {

                    Field field = null;
                    field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                    field.setAccessible(true );
                    field.set(dialog,true );
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                Log.v("tag","取消");
            }
        }).setTitle(dgCaption);
        final AlertDialog alterDialog =builder.create();
        alterDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                //禁止两个按键上获取焦点，不然扫描框里就会失去焦点,在OnShow之前;
                System.out.println("alterDialog-setOnShowListener");
            }
        });
        alterDialog.show();
        //此处设置位置窗体大小
        WindowManager.LayoutParams params = alterDialog.getWindow().getAttributes();
        params.width = 800;
        params.height = 650 ;
        alterDialog.getWindow().setAttributes(params);
        selectTempletList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    view.setSelected(true);
                    if (selectJSON.optJSONObject(position).has("WorkNo")==true)
                        selWorkNo=selectJSON.optJSONObject(position).getString("WorkNo");
                    if (selectJSON.optJSONObject(position).has("WorkName")==true)
                        selWorkName=selectJSON.optJSONObject(position).getString("WorkName");
                    if (selectJSON.optJSONObject(position).has("PrWorkNo")==true)
                        selPrWorkNo=selectJSON.optJSONObject(position).getString("PrWorkNo");
                    TransProcList("AddProc",selPrWorkNo,selWorkNo,selWorkName);
                    alterDialog.dismiss();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        searchOrderProcData(paramOrderNo,paramStyleNo,paramStyleSort);
    }
    //创建列;
    private void CreateListHead() {
        //内容为表头，宽度，自适应;
        if ((headJSON != null) && (headJSON.length() > 0)) {
            int childCount = templetlisthead.getChildCount();
            for (int i = childCount - 1; i >= 0; i--) {
                View view = templetlisthead.getChildAt(i);
                if (view instanceof TextView) {
                    templetlisthead.removeViewAt(i);
                }
            }
            //创建列
            String TitleText,TitleName;
            float  txtWidth;
            int TxtSize,AutoZoom,Align;
            for (int i=0;i<headJSON.length();i++)
                if (headJSON.optJSONObject(i).has("TitleText") == true) {
                    try {
                        TitleName = headJSON.optJSONObject(i).getString("TitleName");
                        TitleText = headJSON.optJSONObject(i).getString("TitleText");
                        TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                        txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                        AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                        TextView tv = new TextView(getContext());
                        tv.setText(TitleText);
                        tv.setWidth((int) txtWidth);
                        tv.setTextColor(getResources().getColor(R.color.white));
                        tv.setTextSize(TxtSize);
                        if (headJSON.optJSONObject(i).has("Align")==true) {
                            Align = headJSON.optJSONObject(i).getInt("Align");
                            switch (Align) {
                                case 0:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                    break;
                                case 1:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                    break;
                                case 2:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                    break;
                                default:
                                    tv.setGravity(Gravity.CENTER_VERTICAL);
                                    break;
                            }
                        }
                        //自定义文字颜色;
                        if (headJSON.optJSONObject(i).has("Color")==true){
                            tv.setTextColor(GetColorValue( headJSON.optJSONObject(i).getString("Color")));
                        }
                        //添加到View中;
                        if (AutoZoom==1) templetlisthead.addView(tv,new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                        else templetlisthead.addView(tv);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            templetlisthead.postInvalidate();
        }
    }

    //判断是否为数字
    public static boolean isNumer(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()>=7)){
            PenColor=Color.parseColor(StrPenColor);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }
    //刷新缸布列表;
    private void searchOrderProcData(String paramOrderNo,String paramStyleNo,String paramStyleSort)
    {
        String SqlComm="Exec KeyPoint_TransPrintSelectProc @OrderNO='" + paramOrderNo
                +"',@StyleNo='" + paramStyleNo+"',@StyleSort='" + paramStyleSort
                +"',@OPERTYPE='SelectList',@UserNo='"+curLoginUserNo
                +"',@UserName='"+curLoginUser+ "',@CPUID='"+CPUID+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    private void TransProcList(String paramOperType,String paramPrWorkNo,String paramWorkNo,String paramWorkName) {
        try {
            procJSON=new JSONArray("[]");
            ProcListAdapter procListAdapter = new ProcListAdapter(getActivity());
            procList.setAdapter(procListAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm="Exec KeyPoint_TransWorkScan @OPERTYPE='"+paramOperType.toUpperCase()
                +"',@OrderNo='"+txt_OrderNo.getText().toString()
                +"',@StyleNo='"+txt_StyleNo.getText().toString()
                +"',@StyleSort='"+txt_StyleSort.getText().toString()
                +"',@PrWorkNo='"+paramPrWorkNo
                +"',@WorkNo='"+paramWorkNo+"',@WorkName='"+paramWorkName
                +"',@UserNo='"+curLoginUserNo+"',@UserName='"+curLoginUser
                +"',@CPUID='"+CPUID+ "',@TermNo='"+MainApplication.TermNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                //任意消息来均置焦点
                if (edt_barcode.isFocused()==false) setEditBarcodeFocus();
                else edt_barcode.selectAll();
                System.out.println("收到的消息是："+msg.what);
                int msgId = msg.what;
                switch (msgId) {
                    case MSG_SCANBARCODE:
                        fillFormtext();
                        break;
                    case MSG_PROCLIST:
                        if (procJSON!=null) {
                            ProcListAdapter procListAdapter = new ProcListAdapter(getActivity());
                            procList.setAdapter(procListAdapter);
                        }
                        break;
                    case MSG_SelectData:
                        //显示表明细
                        if (selectJSON!=null) {
                            SelectTempletListAdapter selectTempletListAdapter = new SelectTempletListAdapter(getContext());
                            selectTempletList.setAdapter(selectTempletListAdapter);
                        }
                        break;
                    case MSG_TotalData:
                        if(totalJSON!=null) {
                            TotalListAdapter totalListAdapter = new TotalListAdapter(getContext());
                            totalList.setAdapter(totalListAdapter);
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    };


    //自定义适配器;
    public final class TotalListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public TotalListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return totalJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return totalJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.fragment_trans_scan_totalitem, null, false);
            int pullVatListWidth=parent.getWidth();
            int color = getResources().getColor(R.color.text_black);
            int backcolor = getResources().getColor(R.color.content);
            ViewHolder holder = new ViewHolder();
            holder.btn_delItem = view.findViewById(R.id.btn_delItem);
            holder.btn_delItem.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v) {
                         //执行删除过程；
                        AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                                .setTitle("系统提示").setMessage("您确定要删除当前扫描记录?")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        try {
                                            String workNo = totalJSON.getJSONObject(position).getString("WorkNo");
                                            String workName = totalJSON.getJSONObject(position).getString("WorkName");
                                            String orderNo = totalJSON.getJSONObject(position).getString("OrderNo");
                                            DeleteTotalRecord(orderNo,workNo,workName);
                                            totalJSON.remove(position);
                                            ((BaseAdapter)totalList.getAdapter()).notifyDataSetChanged();
                                        }
                                        catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                        return;
                                    }
                                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                })  .create(); // 创建对话框
                        alertDialog.show(); // 显示对话框
                }
            });

            view.setTag(holder);
            String tmpValue;
            try {
                Log.d("msg", "getView()a----------------------------------------------------->" + position);
                Log.d(TAG, "getView()----------------------------------------------------->" + position);
                if (totalJSON.optJSONObject(position).has("ConColor") == true) {
                    tmpValue = totalJSON.optJSONObject(position).getString("ConColor");
                    color=GetColorValue(tmpValue);
                }
                if (totalJSON.optJSONObject(position).has("SerNo") == true) {
                    ((TextView)view.findViewById(R.id.text_view_SerNo)).setText(totalJSON.optJSONObject(position).getString("SerNo"));
                    ((TextView)view.findViewById(R.id.text_view_SerNo)).setTextColor(color);
                }
                if (totalJSON.optJSONObject(position).has("OrderNo") == true) {
                    ((TextView)view.findViewById(R.id.text_view_OrderNo)).setText(totalJSON.optJSONObject(position).getString("OrderNo"));
                    ((TextView)view.findViewById(R.id.text_view_OrderNo)).setTextColor(color);
                }
                if (totalJSON.optJSONObject(position).has("WorkNo") == true) {
                    ((TextView)view.findViewById(R.id.text_view_WorkNo)).setText(totalJSON.optJSONObject(position).getString("WorkNo"));
                    ((TextView)view.findViewById(R.id.text_view_WorkNo)).setTextColor(color);
                }
                if (totalJSON.optJSONObject(position).has("WorkName") == true) {
                    ((TextView)view.findViewById(R.id.text_view_WorkName)).setText(totalJSON.optJSONObject(position).getString("WorkName"));
                    ((TextView)view.findViewById(R.id.text_view_WorkName)).setTextColor(color);
                }
                if (totalJSON.optJSONObject(position).has("SAMValue") == true) {
                    ((TextView)view.findViewById(R.id.text_view_SAMValue)).setText(totalJSON.optJSONObject(position).getString("SAMValue"));
                    ((TextView)view.findViewById(R.id.text_view_SAMValue)).setTextColor(color);
                }
                if (totalJSON.optJSONObject(position).has("Number") == true) {
                    ((TextView)view.findViewById(R.id.text_view_Number)).setText(totalJSON.optJSONObject(position).getString("Number"));
                    ((TextView)view.findViewById(R.id.text_view_Number)).setTextColor(color);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","TotalListAdapter_position:"+position);
            return view;
        }

        //提取出来方便点
        public final class ViewHolder {
            public Button btn_delItem;
        }
    }


    private void DeleteTotalRecord(String paramOrderNo,String paramWorkNo,String paramWorkName){
        String SqlComm="Exec KeyPoint_TransDelRecord  @OrderNo='" + paramOrderNo + "',@WorkNo='" + paramWorkNo+ "',@WorkName='" + paramWorkName
                + "',@OPERTYPE='DeleteRec',@UserNo='"+curLoginUserNo+ "',@KeyGuid='"+KeyGuid+"',@TermNo='"+MainApplication.TermNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);

    }


    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        System.out.println("SQLComm:"+SQLComm);
        Runnable run = new Runnable() {
            @Override
            public synchronized void run() {
                try{
                    reentrantLock.lock();
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        String OperType="";
                        if (jsonArray.optJSONObject(0).has("OperType")==true)  OperType=jsonArray.optJSONObject(0).getString("OperType");
                        if (jsonArray.optJSONObject(0).has("OPERTYPE")==true)  OperType=jsonArray.optJSONObject(0).getString("OPERTYPE");
                        if (OperType.toUpperCase().equals("SCANBARCODE")||OperType.toUpperCase().equals("CLEARPROC")
                                ||OperType.toUpperCase().equals("GETPROC")||OperType.toUpperCase().equals("ADDPROC")
                                ||OperType.toUpperCase().equals("DeleteRec".toUpperCase())) {
                            resultJSON=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_SCANBARCODE;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                            return;
                        }
                        if (OperType.toUpperCase().equals("PROCLIST"))
                        {
                            procJSON =jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_PROCLIST;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                            return;
                        }
                        if(OperType.toUpperCase().equals("SelectList".toUpperCase())){
                            selectJSON =jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_SelectData;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                            return;
                        }
                        if(OperType.toUpperCase().equals("TotalList".toUpperCase())){
                            totalJSON =jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_TotalData;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                            return;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    reentrantLock.unlock();
                }finally {
                    reentrantLock.unlock();
                }

            }

        };
        new Thread(run).start();
    }




    //订单表格适配器;
    public final class ProcListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public ProcListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return procJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return procJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.fragment_trans_scan_prochead, null, false);
            int pullVatListWidth=parent.getWidth();
            convertView.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,(int)(38)));
            int color = getResources().getColor(R.color.text_black);
            String tmpValue;
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                if (procJSON.optJSONObject(position).has("ConColor")==true) {
                    tmpValue = procJSON.optJSONObject(position).getString("ConColor").toString();
                    if (tmpValue.equals("1"))
                        color = getResources().getColor(R.color.text_blue);
                    if (tmpValue.equals("2"))
                        color = getResources().getColor(R.color.text_red);
                    if (tmpValue.equals("3"))
                        color = getResources().getColor(R.color.text_gray);
                    if (tmpValue.equals("0"))
                        color = getResources().getColor(R.color.text_black);
                }
                TextView tv = (TextView) convertView.findViewById(R.id.text_view_SerNo);// 显示文字
                if (procJSON.optJSONObject(position).has("SerNo")==true)
                    tv.setText(procJSON.optJSONObject(position).get("SerNo").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.text_view_WorkNo);// 显示文字
                if (procJSON.optJSONObject(position).has("WorkNo")==true)
                    tv.setText(procJSON.optJSONObject(position).get("WorkNo").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.text_view_WorkName);// 显示文字
                if (procJSON.optJSONObject(position).has("WorkName")==true)
                    tv.setText(procJSON.optJSONObject(position).get("WorkName").toString());
                tv.setTextColor(color);

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","ProcListAdapter_position:"+position);
            return convertView;
        }
    }


    //清除界面显示内容
    private void clearFormText(){
        txt_HintInfo.setText("");
        txt_OrderNo.setText("");
        txt_StyleNo.setText("");
        txt_StyleSort.setText("");
        txt_DBH.setText("");
        txt_PO.setText("");
        txt_Color.setText("");
        txt_Size.setText("");
        txt_ReadyScan.setText("");
        txt_OwenNum.setText("");
        txt_HintInfo.setText("");
    }

    //填充界面显示内容;
    private void fillFormtext(){
        if (resultJSON.length()>0)
        {
            try {
                if (resultJSON.getJSONObject(0).has("OrderNo")==true) txt_OrderNo.setText(resultJSON.getJSONObject(0).getString("OrderNo"));
                if (resultJSON.getJSONObject(0).has("StyleNo")==true) txt_StyleNo.setText(resultJSON.getJSONObject(0).getString("StyleNo"));
                if (resultJSON.getJSONObject(0).has("StyleSort")==true) txt_StyleSort.setText(resultJSON.getJSONObject(0).getString("StyleSort"));
                if (resultJSON.getJSONObject(0).has("PO")==true) txt_PO.setText(resultJSON.getJSONObject(0).getString("PO"));
                if (resultJSON.getJSONObject(0).has("Color")==true) txt_Color.setText(resultJSON.getJSONObject(0).getString("Color"));
                if (resultJSON.getJSONObject(0).has("Size")==true) txt_Size.setText(resultJSON.getJSONObject(0).getString("Size"));
                if (resultJSON.getJSONObject(0).has("DBH")==true) txt_DBH.setText(resultJSON.getJSONObject(0).getString("DBH"));
                if (resultJSON.getJSONObject(0).has("ReadyScan")==true) txt_ReadyScan.setText(resultJSON.getJSONObject(0).getString("ReadyScan"));
                if (resultJSON.getJSONObject(0).has("OwenNum")==true) txt_OwenNum.setText(resultJSON.getJSONObject(0).getString("OwenNum"));
                if (resultJSON.getJSONObject(0).has("HintInfo")==true) txt_HintInfo.setText(resultJSON.getJSONObject(0).getString("HintInfo"));
                if (resultJSON.getJSONObject(0).has("LoadProc")==true) {
                    if (resultJSON.getJSONObject(0).getString("LoadProc").toUpperCase().equals("YES"))
                        TransProcList("GetProc","","","");
                }
                if (resultJSON.getJSONObject(0).has("ClearProc")==true) {
                    if (resultJSON.getJSONObject(0).getString("ClearProc").toUpperCase().equals("YES")){
                        procJSON=new JSONArray("[]");
                        ProcListAdapter procListAdapter = new ProcListAdapter(getContext());
                        procList.setAdapter(procListAdapter);
                    }
                }
                if (resultJSON.getJSONObject(0).has("LoadTotal")==true) {
                    if (resultJSON.getJSONObject(0).getString("LoadTotal").toUpperCase().equals("YES"))
                        refreshTotal();
                }
                if (resultJSON.getJSONObject(0).has("ErrInfo")==true)
                {
                    AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                            .setTitle("系统提示").setMessage(resultJSON.getJSONObject(0).getString("ErrInfo"))
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


    }


    @Override
    public void onStart() {
        super.onStart();
        //设置焦点
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.Start");
        setEditBarcodeFocus();
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.End");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden==false){
            //TransProcList("GetProc","","");
        }
    }
}
